function lazy(node: HTMLImageElement, data: { src?: string; placeholder?: string }): SvelteActionReturnType {
	let frame: number = undefined;
	let once = true;
	// Error Handling
	function handleErr(e: ErrorEvent & { target: HTMLImageElement & EventTarget }) {
		console.error(e.error, e.message);

		node.setAttribute(
			"src",
			"",
		);
	}

	if (IntersectionObserver) {
		const intersectionObserver = new IntersectionObserver(
			(entries) => {
				entries.forEach((entry, i) => {
					const target = entry.target as HTMLImageElement;
					if (entry.isIntersecting && once === true) {
						target.src = data.src;
						once = false;
						intersectionObserver.unobserve(node);
					}
				});
			},
			{
				rootMargin: "85px 200px",
				threshold: 0.1,
			},
		);

		intersectionObserver.observe(node);
		return {
			update(data) {
				// console.log(data)
				frame = requestAnimationFrame(() => node.setAttribute("src", data?.src));
			},
			destroy() {
				if (frame !== undefined) {
					cancelAnimationFrame(frame);
				}
				intersectionObserver && intersectionObserver.unobserve(node);
			},
		};
	}
	node.addEventListener("error", handleErr);
}
export default lazy;
